﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AmkeniCrossLoginApplication.Data_Access;

namespace AmkeniCrossLoginApplication.Amkeni_Monitoring_Plan
{
    public partial class AddNewIndicatorToActivity : System.Web.UI.Page
    {
        Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

        /*protected void Page_PreInit(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(Request.QueryString["activity"]))
            {
                //ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
                //            "Error",
                //            "alert('You Cannot access this page')", true);

                //Response.Redirect("../Amkeni_Monitoring_Plan/WorkPlanView.aspx", true);

                string message = "You Cannot Access This Page";
                string url = "../Amkeni_Monitoring_Plan/WorkPlanView.aspx";
                string script = "window.onload = function(){ alert('";
                script += message;
                script += "');";
                script += "window.location = '";
                script += url;
                script += "'; }";
                ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
            }
        }*/

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(Request.QueryString["activity"]))
            {
                /*ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
                            "Error",
                            "alert('You Cannot access this page')", true);

                Response.Redirect("../Amkeni_Monitoring_Plan/WorkPlanView.aspx", true);*/

                string message = "You Cannot Access This Page";
                string url = "../Amkeni_Monitoring_Plan/WorkPlanView.aspx";
                string script = "window.onload = function(){ alert('";
                script += message;
                script += "');";
                script += "window.location = '";
                script += url;
                script += "'; }";
                ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
            }
            else
            {
                if (!IsPostBack)
                {
                    ActivityDataSource.WhereParameters.Clear();
                    ActivityDataSource.AutoGenerateWhereClause = true;
                    ActivityDataSource.WhereParameters.Add("monitoring_plan_id", TypeCode.Int32, Request.QueryString["activity"]);

                    IndicatorDataSource.WhereParameters.Clear();
                    IndicatorDataSource.AutoGenerateWhereClause = true;
                    IndicatorDataSource.WhereParameters.Add("monitoring_plan_id", TypeCode.Int32, Request.QueryString["activity"]);

                    if (IndicatorList.SelectedValue.Equals("N/A"))
                    {
                        ProcessIndicatorTextBox.Enabled = true;
                    }
                    else
                    {
                        ProcessIndicatorTextBox.Enabled = false;
                    }
                }
            }
        }

        protected void OutputList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string outputID = OutputList.SelectedValue.Trim();

            var outputIndicators = from data in db.indicators
                                   where data.output_id == outputID && data.indicator_type_id == 1
                                   select new
                                   {
                                       data.indicator_id,
                                       data.output_indicator_id
                                   };

            IndicatorList.DataSource = outputIndicators.ToList();
            IndicatorList.DataBind();
            IndicatorLabel.Text = string.Empty;
            ProcessIndicatorTextBox.Enabled = true;

            var outputName = (from data in db.programme_output
                              where data.output_id == outputID
                              select new { data.name }).FirstOrDefault();
            if (outputName == null)
            {
                OutputLabel.Text = "N/A";
            }
            else
            {
                OutputLabel.Text = outputName.name;
            }
        }

        protected void OutcomeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (OutcomeList.SelectedValue.Trim() != "N/A")
            {
                int outcomeID = int.Parse(OutcomeList.SelectedValue.Trim());

                var selectedOutputs = from data in db.programme_output
                                      where data.outcome_id == outcomeID
                                      select new { data.output_id, data.name };

                OutputList.Items.Clear();
                OutputList.DataSource = selectedOutputs.ToList();
                OutputList.DataBind();
                OutputLabel.Text = string.Empty;

                IndicatorList.Items.Clear();
                IndicatorList.DataSource = null;
                IndicatorList.DataBind();
                IndicatorLabel.Text = string.Empty;
                ProcessIndicatorTextBox.Enabled = true;

                var outcomeName = (from data in db.programme_outcome
                                   where data.outcome_id == outcomeID
                                   select new { data.name }).FirstOrDefault();
                if (outcomeName == null)
                {
                    OutcomeLabel.Text = "N/A";
                }
                else
                {
                    OutcomeLabel.Text = outcomeName.name;
                }
            }
            else
            {
                OutputList.Items.Clear();
                OutputList.DataSource = null;
                OutputList.DataBind();
                OutputLabel.Text = string.Empty;

                IndicatorList.Items.Clear();
                IndicatorList.DataSource = null;
                IndicatorList.DataBind();
                IndicatorLabel.Text = string.Empty;

                OutcomeLabel.Text = "N/A";
            }
        }

        protected void IndicatorList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IndicatorList.SelectedValue.Trim() != "N/A")
            {
                int indicatorID = int.Parse(IndicatorList.SelectedValue.Trim());
                var indicatorName = (from data in db.indicators
                                     where data.indicator_id == indicatorID
                                     select new { data.name }).FirstOrDefault();
                IndicatorLabel.Text = indicatorName.name;
                ProcessIndicatorTextBox.Text = string.Empty;
                ProcessIndicatorIdHiddenField.Value = null;
                ProcessIndicatorTextBox.Enabled = false;
            }
            else
            {
                IndicatorLabel.Text = "N/A";
                ProcessIndicatorTextBox.Enabled = true;
            }
        }

        private void SetProcessIndicatorId(string processIndicator)
        {
            //try
            //{
            //int id;
            var id = (from data in db.indicators
                      where data.indicator_type_id == 2 && data.name.Trim() == processIndicator.Trim()
                      select new
                      {
                          data.indicator_id
                      }).SingleOrDefault();
            if (id != null)
            {
                ProcessIndicatorIdHiddenField.Value = id.indicator_id.ToString().Trim();
            }
            else if (id == null)
            {
                ProcessIndicatorIdHiddenField.Value = null;
            }
            //}
            //catch (NullReferenceException ex)
            //{
            //    return;
            //}
        }

        protected void ProcessIndicatorTextBox_TextChanged(object sender, EventArgs e)
        {
            /*if (GetProcessIndicatorId(ProcessIndicatorTextBox.Text.Trim()) != null)
            {
                ProcessIndicatorIdHiddenField.Value = GetProcessIndicatorId(ProcessIndicatorTextBox.Text.Trim()).ToString();
            }
            else
            {
                ProcessIndicatorIdHiddenField.Value = null;
            }*/
            SetProcessIndicatorId(ProcessIndicatorTextBox.Text.Trim());
            if (ProcessIndicatorTextBox.Text.Trim() != string.Empty)
            {
                IndicatorList.Enabled = false;
            }
            else
            {
                IndicatorList.Enabled = true;
            }
        }

        protected void IPList_DataBound(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            int x;
            if (ddl != null)
            {
                foreach (ListItem li in ddl.Items)
                {
                    if (int.TryParse(li.Value.Trim(), out x))
                    {
                        int id = int.Parse(li.Value.Trim());
                        string name = (from data in db.implementing_partner
                                       where data.ip_id == id
                                       select data.name).FirstOrDefault();
                        li.Attributes["title"] = name;
                    }
                }
            }
        }

        protected void OutcomeList_DataBound(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            int x;
            if (ddl != null)
            {
                foreach (ListItem li in ddl.Items)
                {
                    if (int.TryParse(li.Value.Trim(), out x))
                    {
                        int id = int.Parse(li.Value.Trim());
                        string name = (from data in db.programme_outcome
                                       where data.outcome_id == id
                                       select data.name).FirstOrDefault();
                        li.Attributes["title"] = name;
                    }
                }
            }
            ddl.Items.Insert(0, new ListItem("N/A", "N/A"));
            ddl.SelectedIndex = 0;
        }

        protected void OutputList_DataBound(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            if (ddl != null)
            {
                foreach (ListItem li in ddl.Items)
                {
                    string id = li.Value.Trim();
                    string name = (from data in db.programme_output
                                   where data.output_id == id
                                   select data.name).FirstOrDefault();
                    li.Attributes["title"] = name;
                }
            }
            ddl.Items.Insert(0, new ListItem("N/A", "N/A"));
            ddl.SelectedIndex = 0;
        }

        protected void IndicatorList_DataBound(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            if (ddl != null)
            {
                foreach (ListItem li in ddl.Items)
                {
                    int id = int.Parse(li.Value.Trim());
                    string name = (from data in db.indicators
                                   where data.indicator_id == id
                                   select data.name).FirstOrDefault();
                    li.Attributes["title"] = name;
                }
            }
            ddl.Items.Insert(0, new ListItem("N/A", "N/A"));
            ddl.SelectedIndex = 0;
        }

        protected void IndicatorCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if ((IndicatorList.SelectedValue == "N/A" && ProcessIndicatorTextBox.Text.Trim() == string.Empty)
                || (IndicatorList.SelectedValue != "N/A" && ProcessIndicatorTextBox.Text.Trim() != string.Empty))
            {
                args.IsValid = false;
            }
            else
            {

            }
        }

        protected void SaveIndicatorBtn_Click(object sender, EventArgs e)
        {
            activity_indicator_connector ind = new activity_indicator_connector();
            int monitoringPlanID = int.Parse(Request.QueryString["activity"].Trim());

            try
            {
                if (IndicatorList.SelectedValue.Trim() != "N/A")
                {
                    ind.monitoring_plan_id = monitoringPlanID;
                    ind.outcome_id = int.Parse(OutcomeList.SelectedValue.Trim());
                    ind.output_id = OutputList.SelectedValue.Trim();
                    ind.indicator_id = int.Parse(IndicatorList.SelectedValue.Trim());
                }
                else if (ProcessIndicatorTextBox.Text.Trim() != string.Empty)
                {
                    if (ProcessIndicatorIdHiddenField.Value.Trim() != null || ProcessIndicatorIdHiddenField.Value.Trim() != "")
                    {
                        int num;
                        if (int.TryParse(ProcessIndicatorIdHiddenField.Value.Trim(), out num))
                        {
                            ind.indicator_id = num;
                            ind.monitoring_plan_id = monitoringPlanID;
                            ind.outcome_id = int.Parse(OutcomeList.SelectedValue.Trim());
                            ind.output_id = OutputList.SelectedValue.Trim();
                        }
                        else
                        {
                            indicator newProcessIndicator = new indicator();
                            //Types of Indicators ids
                            //1 => programme output indicator
                            //2 => process indicator
                            newProcessIndicator.indicator_type_id = 2;
                            newProcessIndicator.name = ProcessIndicatorTextBox.Text.Trim();
                            if (OutputList.SelectedValue.Trim() != "N/A")
                            {
                                newProcessIndicator.output_id = OutputList.SelectedValue.Trim();
                            }
                            db.indicators.Add(newProcessIndicator);

                            ind.indicator = newProcessIndicator;
                            ind.monitoring_plan_id = monitoringPlanID; 
                            ind.outcome_id = int.Parse(OutcomeList.SelectedValue.Trim());
                            ind.output_id = OutputList.SelectedValue.Trim();
                        }
                    }
                }
                db.activity_indicator_connector.Add(ind);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (Page.IsValid)
                {
                    var _ind = from data in db.activity_indicator_connector
                               where data.indicator_id == ind.indicator_id && data.monitoring_plan_id == monitoringPlanID
                               select data;
                    if (_ind.Count() > 0)
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), 
                            "Error", 
                            "alert('The Activity already has that indicator, Select another indicator or click on the Return button if you are done!.')", true);
                    }
                    else
                    {
                        db.SaveChanges();
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success", "alert('Data Has been saved')", true);
                        IndicatorGridView.DataBind();
                    }
                }
            }
        }

        protected void ReturnBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Amkeni_Monitoring_Plan/New_Data.aspx", true);
        }

        protected void ActivityDetailsView_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
        {
            if (e.AffectedRows == 1)
            {
                ScriptManager.RegisterClientScriptBlock(
                    this,
                    this.GetType(),
                    "Success",
                    "alert('Activity Has been deleted') window.location='" +
                    Request.ApplicationPath + "/Amkeni_Monitoring_Plan/WorkPlanView.aspx';", true);
            }
        }
    }
}